﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using MyIni;
using CadStrategy2013.DxfData;
using System.Windows.Forms;

namespace CadStrategy2013
{
    public class Cgq2013
    {
        private string m_id;

        public string Id
        {
            get { return m_id; }
            set { m_id = value; }
        }


        public List<DevClass> DevList = new List<DevClass>();
        public event EventHandler DealDataEvent;
        public event EventHandler WriteDxfEvent;
        public static string strTxjNo;
        public static int bianHao;
        public static string bNo;
        public static void SetBianHao()
        {
            //bianHao++;
            if (bianHao > 33)
            {
                bianHao = 2;
                switch (strTxjNo)
                {
                    case "I":
                        strTxjNo = "II";
                        break;
                    case "II":
                        strTxjNo = "III";
                        break;
                    case "III":
                        strTxjNo = "IV";
                        break;
                    case "IV":
                        strTxjNo = "V";
                        break;
                    case "V":
                        strTxjNo = "VI";
                        break;
                    case "VI":
                        strTxjNo = "VII";
                        break;
                    case "VII":
                        strTxjNo = "VIII";
                        break;
                    case "VIII":
                        strTxjNo = "VIIII";
                        break;
                    default:
                        strTxjNo = "";
                        break;
                }
            }
            bNo = strTxjNo + "-" + bianHao++;
        }
        public Dictionary<string, int> portDevCountDic = new Dictionary<string, int>();
        public Dictionary<string, string> portDic;
        #region 相关属性
        string m_secName;

        public string SecName
        {
            get { return m_secName; }
            set { m_secName = value; }
        }
        string m_path;
        public string Path
        {
            get { return m_path; }
            set { m_path = value; }
        }
        string m_savePath;
        public string SavePath
        {
            get { return m_savePath; }
            set { m_savePath = value; }
        }
        string m_stationName;
        public string StationName
        {
            get { return m_stationName; }
            set { m_stationName = value; }
        }
        string m_templateFileName;
        public string TemplateFileName
        {
            get { return m_templateFileName; }
            set { m_templateFileName = value; }
        }
        int m_banCount;
        public int BanCount
        {
            get { return m_banCount; }
            set { m_banCount = value; }
        }
        int m_ShiJiBanCount;
        public int ShiJiBanCount
        {
            get { return m_ShiJiBanCount; }
            set { m_ShiJiBanCount = value; }
        }
        int m_ShiJiTuZhiCount;
        public int ShiJiTuZhiCount
        {
            get { return m_ShiJiTuZhiCount; }
            set { m_ShiJiTuZhiCount = value; }
        }
        int m_banDevCount;
        public int BanDevCount
        {
            get { return m_banDevCount; }
            set { m_banDevCount = value; }
        }
        int m_banDevPeiCount;
        public int BanDevPeiCount
        {
            get { return m_banDevPeiCount; }
            set { m_banDevPeiCount = value; }
        }
        int m_banDevJkbCount;
        public int BanDevJkbCount
        {
            get { return m_banDevJkbCount; }
            set { m_banDevJkbCount = value; }
        }
        string m_banDevProp;
        public string BanDevProp
        {
            get { return m_banDevProp; }
            set { m_banDevProp = value; }
        }
        int m_fileNameIndex;
        /// <summary>
        /// 确定生成的cad文件的序号。对于较大的车站一个类型的cad图，可能有多个。
        /// 例如 道岔表示1.dxf 道岔表示2.dxf.
        /// 
        /// </summary>
        public int FileNameIndex
        {
            get { return m_fileNameIndex; }
            set { m_fileNameIndex = value; }
        }

        public string[] ShiJiBanHao;
        public DxfDataClass m_dxfDataClass;
        IniFile m_inicfg;
        public IniFile Inicfg
        {
            get { return m_inicfg; }
            //set { m_inicfg = value; }
        }
        #endregion
        public Cgq2013(string secname)
        {
            m_secName = secname;
            m_path = "./";
            m_inicfg = new IniFile(m_path + "\\template\\cfg.txt");
            GetCfg();
            GetDxfData();
            GetFileNameIndex();
        }

        public Cgq2013(string secname, Dictionary<string, string> dic)
        {
            m_secName = secname;
            m_path = "./";
            m_inicfg = new IniFile(m_path + "\\template\\cfg.txt");
            GetCfg();
            GetDxfData();
            GetFileNameIndex();
            if (dic.Count == 0)
            {
                IniFile f = new IniFile(m_path +"\\"+StationName+ "\\统计.txt");
                f.Load();
                string str=f.GetString(secname, "编号");
                string[] strs = str.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (string s in strs)
                {
                    dic.Add(s, secname);
                }
            }
            portDic = dic;
        }

        public Cgq2013(string secname, string id)
        {
            m_secName = secname;
            m_path = "./";
            m_inicfg = new IniFile(m_path + "\\template\\cfg.txt");
            GetCfg();
            GetDxfData();
            GetFileNameIndex();
            Id = id;
        }
        public void OnDealData(object sender,EventArgs e )
        {
            if (DealDataEvent != null)
            {
                DealDataEvent(sender,e);
            }
        }
        public void OnWriteDxf(object sender, EventArgs e)
        {
            if (WriteDxfEvent != null)
            {
                WriteDxfEvent(sender, e);
            }
        }
        /// <summary>
        /// 基类主要是读取全局.ini中的配置
        /// </summary>
        public virtual void GetCfg()
        {
            IniFile ini = new IniFile("./\\全局.ini");
            StationName = ini.GetString("全局", "站名", "XXX");
            SavePath = ini.GetString("全局", "保存路径", "d:\\");// +StationName;
            if (!SavePath.EndsWith("\\"))
            {
                SavePath += "\\";
            }
            if (!Directory.Exists(SavePath))
            {
                Directory.CreateDirectory(SavePath);
            }
            strTxjNo = ini.GetString("全局", "起始通信机", "");
            bianHao = ini.GetInt16("全局", "起始板编号", 0);
            bNo = strTxjNo + "-" + bianHao;
            GetCfg(m_secName);
           // CopyCommonFile();
        }
       
        public void CopyCommonFile()
        {
            string sourcePath = "./\\template\\";
            IniFile inifile = new IniFile(sourcePath+"cfg.txt");
            string str = inifile.GetString("公共部分", "文件", "");
            string[] strs = str.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            foreach (string s in strs)
            {
                if (File.Exists(SavePath+s+".dwg") == false)
                {
                    try
                    {
                        File.Copy(sourcePath + s + ".dwg", SavePath + s + ".dwg");
                    }
                    catch 
                    {
                    }
                }
            }
        }
        /// <summary>
        ///读取\\template\\cfg.txt中section名为strSec中的值，对不同cad图进行基本配置 
        /// </summary>
        /// <param name="strSec"></param>
        public virtual void GetCfg(string strSec)
        {
            TemplateFileName = Inicfg.GetString(strSec, "文件名", "");
            BanCount = Inicfg.GetInt16(strSec, "板数", 0);
            BanDevCount = Inicfg.GetInt16(strSec, "板内设备数", 0);
            BanDevPeiCount = Inicfg.GetInt16(strSec, "每个设备配线端子数", 0);
            BanDevJkbCount = Inicfg.GetInt16(strSec, "每个设备接口板端子数", 0);
            BanDevProp = Inicfg.GetString(strSec, "设备属性", "");
        }
        /// <summary>
        /// 把模板中的数据读入列表
        /// </summary>
        /// <param name="filename"></param>
        /// <returns></returns>
        public  List<string> ReadDxf(string filename)
        {
            List<string> strList = new List<string>();
            using (StreamReader sr = new StreamReader(filename))
            {
                while (sr.Peek() >= 0)
                {
                    strList.Add(sr.ReadLine());
                }
            }
            return strList;
        }
        public virtual List<string> ReadTemplateDxf()
        {
            return null;
        }
        public  void WriteDxf(List<string> list,string filename)
        {
            string str3 = filename;
            try
            {
                if (File.Exists(filename))
                {
                    File.Delete(filename);
                }

                using (StreamWriter sw = new StreamWriter(filename, false))
                //using (StreamWriter sw=File.CreateText(filename))
                {
                    int n=0;
                    foreach (string str in list)
                    {
                        sw.WriteLine(str);
                        OnWriteDxf(this,new WriteDxfArgs("写文件",str,list.Count,++n));
                    }
                }
            }
            catch 
            {
               // Console.WriteLine("The process failed: {0}", e.ToString());
            }
        }
        public virtual void WriteDxf()
        {
            List<string> list1;
            list1 = ReadTemplateDxf();
            List<string> list;
            for (int i = 0; i <=FileNameIndex; i++)
            {
                list = DealData(list1,i);
                WriteDxf(list, SavePath + GetSaveFileName(i));
            }
            MessageBox.Show("ok");
        }
        public virtual string GetSaveFileName(int index)
        {
            return "xxx.dxf";
        }
        public virtual DxfData.DxfDataClass GetDxfData()
        {
            return null;
        }
        public virtual List<string> DealData(List<string> strList)
        {
            List<string> list = new List<string>();
            foreach (string str in strList)
            {
                string str1 = str;
                str1 = ReplacebNo(str1);
                str1 = ReplaceDev(str1);
                str1 = ReplacePei(str1);
                list.Add(str1);
            }
            return list;
        }
        public virtual List<string> DealData(List<string> strList, int i)
        {
            List<string> list = new List<string>();
            int n=0;
            foreach (string str in strList)
            {
                n++;
                string str1 = str;
                str1 = ReplaceStationName(str1);
                str1 = ReplacebNo(str1, i);
                str1 = ReplaceDev(str1, i);
                str1 = ReplaceCPei(str1, i);
                str1 = ReplacePei(str1, i);
                list.Add(str1);
                OnDealData(this,new WriteDxfArgs(m_secName+i.ToString(),str,strList.Count,n));
            }
            return list;
        }
        public virtual string[] GetBianHao()
        {

            if (portDic == null)
            {
                #region 如果没有配置传感器的编号
                if (ShiJiBanHao == null)
                {
                    string[] str = new string[ShiJiBanCount];
                    for (int i = 0; i < ShiJiBanCount; i++)
                    {
                        Cgq2013.SetBianHao();
                        str[i] = Cgq2013.bNo;
                        if (portDevCountDic.ContainsKey(strTxjNo))
                        {
                            if (portDevCountDic[strTxjNo] < bianHao)
                                portDevCountDic[strTxjNo] = bianHao;
                        }
                        else
                        {
                            portDevCountDic.Add(strTxjNo, bianHao);
                        }
                    }
                    ShiJiBanHao = str;
                    IniFile inifile = new IniFile("./\\" + StationName + "\\统计.txt");
                    inifile.WriteValue(SecName, "数量", ShiJiBanHao.Length);
                    try
                    {
                        inifile.WriteValue(SecName, "编号", ShiJiBanHao[0] + " " + ShiJiBanHao[ShiJiBanHao.Length - 1]);

                    }
                    catch
                    {
                        inifile.WriteValue(SecName, "编号", "");
                    }
                    foreach (string strKey in portDevCountDic.Keys)
                    {
                        inifile.WriteValue("port" + strKey, "数量", portDevCountDic[strKey] - 2);
                    }
                }
                return ShiJiBanHao;
                #endregion
            }
            else
            {
                #region 如果配置传感器编号
                string[] strs = new string[portDic.Count];
                int i = 0;
                foreach (string str in portDic.Keys)
                {
                    strs[i++] = str;
                }
                return strs;
                #endregion
            }
        }
        public virtual int GetFileNameIndex()
        {
            try
            {
                FileNameIndex = (ShiJiBanCount - 1) / BanCount;
            }
            catch
            {
                return 0;
            }
            return FileNameIndex;
        }
        public string ReplaceStationName(string str)
        {
            if (str.Contains("XX站"))
            {
                str = str.Replace("XX站",StationName);
                return str;
            }
            return str;
        }
        public virtual string ReplacebNo(string str,int fi=0)
        {
            string[] strs = GetBianHao();
            for (int i = 1; i <= BanCount; i++)
            {
                int n = i;// +fi * BanCount;
                if (str.Contains("bNo" + n+">"))
                {
                    if ((i+fi*BanCount) <= ShiJiBanCount)
                    {
                        return str = str.Replace("bNo" + n + ">", strs[(fi*BanCount)+i - 1]);
                    }
                    else
                    {
                        return "";// str = str.Replace(str, "");
                    }
                }
            }
            return str;
        }
        public virtual string ReplaceDev(string str2,int fi=0)
        {
            string str = str2;
            for (int j = 1; j <= BanCount; j++)
            {
                int nj = j;// -fi * BanCount;
                for (int i = 1; i <= BanDevCount; i++)
                {
                    string str1 = "dev" + nj.ToString() + "-" + i.ToString()+">";
                    if (str.Contains(str1))
                    {
                        int index = (fi*BanCount+j - 1) * BanDevCount + i - 1;
                        if (index >= m_dxfDataClass.devList.Count)
                        {
                           return  str ="";
                        }
                        else
                        {
                            try
                            {
                               return str = str.Replace(str1, m_dxfDataClass.devList[index].DevName);
                            }
                            catch 
                            {
                                return str = "";
                            }
                        }
                    }
                }
            }
            return str;
        }
        public virtual string ReplacePei(string str,int fi=0)
        {
            for (int j = 1; j <= BanCount; j++)
            {
                int nj = j;// -fi * BanCount;
                for (int i = 1; i <=BanDevPeiCount * BanDevCount; i++)
                {
                    string str1 = "pei" + nj.ToString() + "-" + i.ToString()+">";
                    if (str.Contains(str1))
                    {
                        int index = (fi * BanCount + j - 1) * BanDevCount + (i - 1) / BanDevPeiCount;
                        if (index >= m_dxfDataClass.devList.Count)
                        {
                            return "";
                        }
                        else
                        {
                            int index1 = (i - 1) % (BanDevPeiCount);//BanDevCount);
                            try
                            {
                                return str = str.Replace(str1, m_dxfDataClass.devList[index].peiList[index1]);
                            }
                            catch 
                            {
                                return "";
                            }
                        }
                    }
                }
            }
            return str;
        }
        public virtual string ReplaceCPei(string str,int fi=0)
        {
            for (int j = 1; j <= BanCount; j++)
            {
                int nj = j;
                for (int i = 1; i <= BanDevJkbCount * BanDevCount; i++)
                {
                    string str1 = "cpei" + nj.ToString() + "-" + i.ToString()+">";
                    if (str.Contains(str1))
                    {
                        int index = (fi * BanCount + j - 1) * BanDevCount + (i - 1) / BanDevJkbCount;
                        if (index >= m_dxfDataClass.devList.Count)
                        {
                            return "";
                        }
                        else
                        {
                            int index1 = (i - 1) % BanDevJkbCount;
                            try
                            {
                                  return  str = str.Replace(str1, m_dxfDataClass.devList[index].cpeiList[index1]);
                            }
                            catch
                            {
                                return "";
                            }
                        }
                    }
                }
            }
            return str;
        }
        public virtual void WriteDwg()
        {
        }

        public virtual void GetDevList(IniFile inifile, int index)
        {
        }
    }
}
